(function( $, undefined ) {

$.widget("ui.area", {
    options : {
        parentImg: null,
        area: null,
        container: null
    },

    _create : function() {
    	var self = this;
    	if (self.options.area) {
	    	this.element
	    	.resizable({
	    		start: function(event, ui){
	    			ui.position.top += self.options.container.scrollTop();
	    		},
	    		stop: function(event, ui){
	    			if (ui.size.height > self.options.parentImg.height()) {
	    				$(this).height(ui.size.height = self.options.parentImg.height());
	    			}
	    	
	    			if (ui.size.width > self.options.parentImg.width()) {
	    				$(this).width(ui.size.width = self.options.parentImg.width());
	    			}
	    			
	    			var coords = self.options.area.attr('coords').split(',');
	    			coords[2] = parseInt(coords[2]) + (ui.size.width - ui.originalSize.width);
	    			coords[3] = parseInt(coords[3]) + (ui.size.height - ui.originalSize.height);
	    			self.options.area.attr('coords', coords.join(','));
	    			self._trigger('resize', event);
	    		}
	    	})
	    	.draggable({
	    		containment: this.options.parentImg,
	    		stop: function(event, ui) {
	    			var coords = self.options.area.attr('coords').split(',');
	    			coords[0] = parseInt(coords[0]) + (ui.position.left - ui.originalPosition.left);
	    			coords[1] = parseInt(coords[1]) + (ui.position.top - ui.originalPosition.top);
	    			coords[2] = parseInt(coords[2]) + (ui.position.left - ui.originalPosition.left);
	    			coords[3] = parseInt(coords[3]) + (ui.position.top - ui.originalPosition.top);
	    			self.options.area.attr('coords', coords.join(','));
	    			self._trigger('drop', event);
	    		}
	    	})
	    	.on('click', function(event) {
	    		self._trigger('drop', event);
	    	});
    	}
    	this.element.hide();
    },
    
    refresh : function() {
    	selfEl = $(this.element);
    	selfEl.removeAttr('style');
    	selfEl.css('cursor', 'move');
    	
    	var coords   = [];
    	var parentEl = this.options.parentImg;
    	if (this.options.area == null) {
    		coords = [0, 0, parentEl.width(), parentEl.height()];
    	} else {
    		coords = this.options.area.attr('coords').split(',');
    	}
		
		var offsetX = parseInt(coords[0]);
		var offsetY = parseInt(coords[1]);
		
		selfEl.width(coords[2] - coords[0]);
		selfEl.height(coords[3] - coords[1]);
		
		selfEl.position({
			of: parentEl,
			my: "left top",
			at: "left top",
			offset: offsetX + " " + offsetY,
			collision: 'none'
		});
    },
    
    destroy: function() {
        $.Widget.prototype.destroy.apply( this, arguments );
    },
});

$.extend($.ui.area, {
    version: "0.1"
});

}(jQuery));